<?php

class Webmix_AdminAlbumController extends Core_Controller_Action_Admin {
	
    public function indexAction() {
		$this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      		->getNavigation('webmix_admin_main', array(), 'webmix_admin_main_music');
		
      	$this->view->formFilter = $formFilter = new Webmix_Form_Admin_Company_Filter();
	    $page = $this->_getParam('page', 1);

	    $table = Engine_Api::_()->getDbtable('musicalbums', 'webmix');
	    $select = $table->select();
	
        // show companies of country
        $country_id = $this->_getParam('id',0);
        if(!empty($country_id)){
            $select->where('country_id = ?', $country_id);
        }
        
        //show tracked company
        $track = $this->_getParam('track',0);
        if(!empty($track)){
            $select->where('track = ?', 1);
        }
                
	    // Process form
	    $values = array();
	    if( $formFilter->isValid($this->_getAllParams()) ) {
	      $values = $formFilter->getValues();
	    }

	    foreach( $values as $key => $value ) {
	      if( null === $value ) {
	        unset($values[$key]);
	      }
	    }
	
	    $values = array_merge(array(
	      'order' => 'musicalbum_id',
	      'order_direction' => 'DESC',
	    ), $values);
	    
	    $this->view->assign($values);
	
	    // Set up select info
	    $select->order(( !empty($values['order']) ? $values['order'] : 'musicalbum_id' ) . ' ' . ( !empty($values['order_direction']) ? $values['order_direction'] : 'DESC' ));
	
	    if( !empty($values['title']) ) {
	      $select->where('title LIKE ?', '%' . $values['title'] . '%');
	    }
	    if( !empty($values['createby']) ) {
	      $select->where('type = ?', $values['createby']);
	    }	    
		if( !empty($values['approve']) ) {
	      $select->where('approve = ?', (int) $values['approve']);
	    }
		if( !empty($values['owner']) ) {
	      $select->from($table->info('name'))
	      		->join('engine4_users as u', 'u.user_id = '.$table->info('name') .'.owner_id', null)
	      		->where('u.displayname LIKE "%'.$values['owner'].'%" or u.username LIKE "%'.$values['owner'].'%"');
	    }
    
    // Make paginator
    $this->view->paginator = $paginator = Zend_Paginator::factory($select);
    $paginator->setItemCountPerPage(100);
    $this->view->paginator = $paginator->setCurrentPageNumber( $page );
    $this->view->formValues = $values;
}
	
  public function deleteAction()
  {
    $id = $this->_getParam('id', null);
    $this->view->company = $company = Engine_Api::_()->getItem('webmix_musicalbum', $id);
    $this->view->form = $form = new Webmix_Form_Admin_Company_Delete();
    $form->setTitle('Delete music album');
    $form->setDescription('Do you want to delete this music album ?.');
    $viewer = Engine_Api::_()->user()->getViewer();
    // deleting user
    //$form->user_id->setValue($id);

    if( !$this->getRequest()->isPost() ) {
        return;
    }
       
    
      $db = Engine_Api::_()->getDbtable('musicalbums', 'webmix')->getAdapter();
      $db->beginTransaction();
      try {
        
        
        $webmixTable = Engine_Api::_()->getDbtable('webmixes','webmix');
        $select = $webmixTable->select()
                              ->where('content_type = 1');
        $rows = $webmixTable->fetchAll($select);
        $wids = array();
        $wids[] = 0;
        foreach($rows as $row){
            $wids[] = $row->webmix_id;
        } 
           
        $blockTable = Engine_Api::_()->getDbtable('blocks','webmix');
        $blockTable->delete(
            array(
                'company_id = ?' => $company->getIdentity(),
                'webmix_id in (?)' => $wids,
            )
            
        );
          
                
        $company->delete();
        
        $db->commit();
      } catch( Exception $e ) {
        $db->rollBack();
        throw $e;
      }
              
      return $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => true,
        'parentRefresh' => true,
        'format'=> 'smoothbox',
        'messages' => array('This album has been successfully deleted.')
      ));       
  }
public function approveAction()
  {
    $id = $this->_getParam('company', null);
    $approve = $this->_getParam('approve', 1);
    $this->view->company = $company = Engine_Api::_()->getItem('webmix_company', $id);
    $this->view->form = $form = new Webmix_Form_Admin_Company_Approve();
    $viewer = Engine_Api::_()->user()->getViewer();
    if(!$approve) $form->setTitle('Un-approve')
    					->setDescription('Are you sure you want to un-approve this company?');
    // deleting user
    //$form->user_id->setValue($id);

    if( $this->getRequest()->isPost() ) {
      $db = Engine_Api::_()->getDbtable('companies', 'webmix')->getAdapter();
      $db->beginTransaction();

      try {
        $company->approve = $approve;
        $company->save();
        
        $db->commit();
      } catch( Exception $e ) {
        $db->rollBack();
        throw $e;
      }
      
      if($approve){
            // Mail gets logged into database, so perform try/catch in this Controller
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            try {
                
              //Find company onwer
              $userTable = Engine_Api::_()->getItemTable('user');
              $owner = $userTable->find($company->owner_id)->getRow(0);
              // Make params
              $mail_settings = array(
                'host' => $_SERVER['HTTP_HOST'],
                'email' => $owner->email,
                'date' => time(),
                'recipient_title' => $owner->getTitle(),
                'recipient_link' => $owner->getHref(),
                'recipient_photo' => $owner->getPhotoUrl('thumb.icon'),
                'sender_title' => $viewer->getTitle(),
                'object_title' => $company->title,
                'sender_email' => $viewer->email,
                'object_link' => $company->getHref(),
              );
        
              if( $viewer && $viewer->getIdentity() ) {
                $mail_settings['sender_title'] .= ' (' . $viewer->email . ')';
              }
              // send email
              Engine_Api::_()->getApi('mail', 'core')->sendSystemRaw(
                $owner->email,
                'notify_webmix_company_approve',
                $mail_settings
              );
              // if the above did not throw an exception, it succeeded
              $db->commit();
            } catch( Zend_Mail_Transport_Exception $e ) {
              $db->rollBack();
              throw $e;
            }        
      }

      
      return $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => true,
        'parentRefresh' => true,
        'format'=> 'smoothbox',
        'messages' => array('This company has been successfully changed.')
      ));
    }
  }
    public function multiModifyAction()
	  {
	    if( $this->getRequest()->isPost() ) {
	      $values = $this->getRequest()->getPost();
	      foreach ($values as $key=>$value) {
	        if( $key == 'modify_' . $value ) {
	          $company = Engine_Api::_()->getItem('webmix_company', (int) $value);
	          if( $values['submit_button_delete'] == 'delete' ) {	            
	          		$company->delete();
	          }
	        }
	      }
	    }	
	    return $this->_helper->redirector->gotoRoute(array('action' => 'index'));
	}
    
    
  public function createAction()
  {
	if( !$this->_helper->requireUser()->isValid() ) {
		return;
	}
    
    $this->view->form = $form = new Webmix_Form_Album_Create();
    
    // Check post
    if(!$this->getRequest()->isPost()){
        return;
    }
    // Check form validate
    if(!$form->isValid($this->getRequest()->getPost())){
        return;
    }
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

    $values = $form->getValues();
   
    $photo_url = '';
    //refresh photo when upload a new one
    if($values['file_id']){
        $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($values['file_id'],'thumb.normal');                            
        $photo_url = $photo->map();
        $this->view->photo_url = $photo_url;               
    }     
    
    $table = Engine_Api::_()->getDbTable('musicalbums','webmix');
    
    
    //check existed company-country-link
    $check = $table->select()
            ->where('`key` = ?',$values['key']);
           
    $check_result = $table->fetchAll($check);
    if(count($check_result)>0){
        $form->addError('Your album key had existed.');
        return;
    }
    
    //save form values
    $db = $table->getAdapter();
    $db->beginTransaction();
    try
    {            
        $company = $table->createRow();
        $company->setFromArray($values);
        $company->type = 'admin';
        $company->approve = 1;
        $company->owner_id = $viewer->getIdentity();
        $company->photo_id = $values['file_id'];
        if (!empty($photo_url)) {
            $company->photo_url =  $photo_url;
        }
        
        $company->save();
        $db->commit();   
        $form->addNotice($this->view->translate('Your company was created successfully.'));                  
        
        //Call hook to set country company_count
        $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCountryCompanyCount', array(
          'country_create' => $values['country_id'],
        ));      
    }
    catch(Exception $e)
    {
        $db->rollBack();
        throw $e;
    }        
          
    //return admin company after create
    return $this->_helper->redirector->gotoRoute(array('module'=>'webmix','controller'=>'album'), 'admin_default', true);

            
  }

  public function editAction(){
    	if( !$this->_helper->requireUser()->isValid() ) {
    		return;
    	}     
        
        //get company_id when edit in Admin
        $company_id = $this->_getParam('company');
        //get photo_id when upload image in admin edit
        $photo_id = $this->_getParam('photo');
        
        $this->view->form = $form = new Webmix_Form_Admin_Company_Edit();
                
        $company = Engine_Api::_()->getItem('webmix_company',$company_id);    
        $form->populate($company->toArray());
        $this->view->company = $company_id;
        if($photo_id){
            $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($photo_id,'thumb.normal');                            
            $photo_url = $photo->map();
            $this->view->photo_url = $photo_url;           
        }
        else{
            $this->view->photo_url = $company->getPhotoUrl('thumb.normal');                        
        }               
               
        // Check post form
        if( !$this->getRequest()->isPost() ) {
          return;
        }
        if( !$form->isValid($this->getRequest()->getPost()) ) {
          return;
        }
        
        $values = $form->getValues();    
        //refresh photo when upload a new one
        if($values['file_id']){
            $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($values['file_id'],'thumb.normal');                            
            $photo_url = $photo->map();
            $this->view->photo_url = $photo_url;               
        }

        //check change country
        if($company->country_id != $values['country_id']){
            $country_id = $company->country_id;
            $country_id_new = $values['country_id'];
        }                
        // Process
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction();        
        
        try{
            $company->setFromArray($values);
            $company->modified_date = date('Y-m-d H:i:s');

            $company->photo_id = $photo_id;    

            $company->save();
            $db->commit();   
            
            //Call hook to set country company_count
            if(isset($country_id) && isset($country_id_new)){
                $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCountryCompanyCount', array(
                  'country' => $country_id,
                  'country_new' => $country_id_new,
                ));                    
            }

            return $this->_forward('success', 'utility', 'core', array(
            'smoothboxClose' => 1000,
            'parentRefresh' => 10,
            'format'=> 'smoothbox',
            'messages' => array('Your changes have been saved.')
            ));
            
        }
        catch(Exception $e)
        {
            $db->rollback();
            throw $e;
        }
    }

  public function getCompanyAction(){
    $name = $this->_getParam('name');
    $id = $this->_getParam('id');
    $action_type = $this->_getParam('action_type');
    $viewer = Engine_Api::_()->user()->getViewer();
    if(!$name && !$id){
        return;
    }
    
    $Company_table = Engine_Api::_()->getDbTable('companies','webmix');     
    //get Hint by company title
    if($name && $name != ""){
        
        $select = $Company_table->select()
                    ->setIntegrityCheck(false)
                    ->from('engine4_webmix_companies as company')
                    ->join('engine4_webmix_countries as country', 'country.country_id = company.country_id',array('country_id','key'))
                    ->where('company.title like ?',$name.'%')
                    ->where('country.selected = 1')
                    ;    
        //not duplicate db when approve 
        $select->where('owner_id = ? OR company.approve = 1 ',$viewer->getIdentity());                        

        
    }
    //get company (to fill) by company_id
    $companies = array();
    if($id){

        $select = $Company_table->select()
                    ->where('company_id = ?',$id.'%');
        $row = $Company_table->fetchAll($select)->getRow(0);
        
        $photo_url = $row->getPhotoUrl('thumb.normal');        
        
        $companies = array(
            'photo_url' => $photo_url,
        );                              
    }
                                            
    // if get company by id
   	$companies = array_merge($Company_table->fetchAll($select)->toArray(), $companies);     
    
    return $this->_helper->json($companies);
    $this->getResponse()->setBody(Zend_Json::encode($companies));
  }
  
  public function uploadAction(){
    if( !$this->_helper->requireUser()->isValid() ) {
    		return;
    	}
    $this->view->type = $type = $this->_getParam('type');
    $this->view->album = $this->_getParam('album');
    $this->view->form = $form = new Webmix_Form_Admin_Company_Upload();   
  }  
  
  public function previewAction(){
        
        $table = Engine_Api::_()->getDbTable('companies','webmix'); 
        $file_id = $table->setPhoto($_FILES['image']); 
        $type = 'thumb.normal';
        $file = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id, $type);
            if( !$file ) {
                return ;
            } 
        //get normal photo to save           
        $file_url = $file->map();
        $this->view->file_url = $file_url;
        $this->view->file_id = $file_id;
        
        //get full size photo to preview
        $preview = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id);
        $preview_url = $preview->map();
        $this->view->preview_url = $preview_url;                
  }
  
  public function trackAction(){

    $id = $this->_getParam('company', null);
    $track = $this->_getParam('track', 1);
    $this->view->company = $company = Engine_Api::_()->getItem('webmix_company', $id);
    $this->view->form = $form = new Webmix_Form_Admin_Company_Track();
    $viewer = Engine_Api::_()->user()->getViewer();
    if(!$track) $form->setTitle('Un-Track')
    					->setDescription('Are you sure you want to un-track this company?');
    // deleting user
    //$form->user_id->setValue($id);

    if( $this->getRequest()->isPost() ) {
      $db = Engine_Api::_()->getDbtable('companies', 'webmix')->getAdapter();
      $db->beginTransaction();

      try {
        $company->track = $track;
        $company->save();
        
        $db->commit();
      } catch( Exception $e ) {
        $db->rollBack();
        throw $e;
      }
      
      return $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => true,
        'parentRefresh' => true,
        'format'=> 'smoothbox',
        'messages' => array('Your changes have been saved successfull.')
      ));
    }
  }
    
    public function mergeAction(){
    	
        if( !$this->_helper->requireUser()->isValid() ) {
    		return;
    	}
        
        $this->view->form = $form = new Webmix_Form_Admin_Company_Merge();
        
        // Check post
        if(!$this->getRequest()->isPost()){
            return;
        }
        $this->view->isValidF = true;
        // Check form validate
        $values = $this->getRequest()->getPost();
        
        if( !empty($values['submit_button_merge']) && $values['submit_button_merge'] == 'merge' ) {	            
            $this->view->ckcompany = $values;
            return;
        }

        if(!$form->isValid($this->getRequest()->getPost())){
            $this->view->isValidF = false;
            return;
        }
         
        $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
    
        $values = $form->getValues();
        
            $ckcompany = explode(",",$values['ckcompany']);
//            echo '<pre>';
//            print_r($values);
//            echo '</br>';
//            print_r($ckcompany);
    
        //refresh photo when upload a new one
        if($values['file_id']){
            $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($values['file_id'],'thumb.normal');                            
            $photo_url = $photo->map();
            $this->view->photo_url = $photo_url;               
        }     
        
        //check if choose create new
        if($values['comp_id'] == 0){
    
            $table = Engine_Api::_()->getDbTable('companies','webmix');
            
            //check existed company-country-link
            $check = $table->select()
                    ->where('country_id = ?',$values['country_id'])
                    ->where('title = ?',$values['title'])
                    ->where('link = ?',$values['link'])
                   
                    //not duplicate db when approve 
                    ->where('owner_id = ? OR approve = 1 ',$viewer->getIdentity())
                    ;
                    
            $check_result = $table->fetchAll($check);
            if(count($check_result)>0){
                $form->addError('Your company-link-country existed.');
                return;
            }
            
            //save form values
            $db = $table->getAdapter();
            $db->beginTransaction();
            try
            {            
                $company = $table->createRow();
                $company->setFromArray($values);
                $company->owner_id = $viewer->getIdentity();
                $company->photo_id = $values['file_id'];
                $company->save();
                $db->commit();   
                $form->addNotice($this->view->translate('Your company created successfully.'));                  
                
                //Call hook to set country company_count
                $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCountryCompanyCount', array(
                  'country_create' => $values['country_id'],
                ));
                      
            }
            catch(Exception $e)
            {
                $db->rollBack();
                throw $e;
            }        
        }
           
        //change company in block
        
        if($values['comp_id'] == 0){
            $company_id_new = $company->company_id;
        }
        else{
            $company_id_new = $values['comp_id'];
        }
        
        foreach($ckcompany as $key=>$company_id){
            $blockTable = Engine_Api::_()->getDbtable('blocks','webmix'); 
            $blockSelect = $blockTable->select()
                            ->where('company_id = ?',$company_id)
                            ->where('company_id <> ?',$company_id_new);
            $rows =  $blockTable->fetchAll($blockSelect);               
            $add_count = count($rows);
            
            
            if($add_count>0){
                
                //edit block                
                $db = $blockTable->getAdapter();
                $db->beginTransaction();
                try
                {   
//                    echo '</br>';
//                    echo 'comp_new'.$company_id_new;
//                    echo 'comp'.$company_id;
                    $update= $blockTable->update(array(
                        'company_id' => $company_id_new,
                    ),array(
                        'company_id = ?'=> $company_id,
                        ));
                    $db->commit();    
                }
                catch(Exception $e)
                {
                    $db->rollBack();
                    throw $e;
                }   
                
                
                //increase add_count of company
                
                $db = Engine_Db_Table::getDefaultAdapter();
                $db->beginTransaction();                    
                try{
//                    echo '</br>';
//                    echo $add_count;
                    $company = Engine_Api::_()->getItem('webmix_company',$company_id_new);
                    $company->add_count = $company->add_count + $add_count;
                    $company->save();   
                    $db->commit();     
                                    
                }
                catch(Exception $e)
                {
                    $db->rollback();
                    throw $e;
                }  
                
                //delete company and decrease company_count  
                
                $db = $blockTable->getAdapter();
                $db->beginTransaction();
                try {
                    
                    $company = Engine_Api::_()->getItem('webmix_company',$company_id);
                    //Call hook to set company add count
                    $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCountryCompanyCount', array(
                      'country_delete' => $company->country_id,
                    )); 
                    
                    $company->delete();            
                    $db->commit();
                } catch( Exception $e ) {
                    $db->rollBack();
                    throw $e;
                }                                 
            }
                                   
        }
        return $this->_helper->redirector->gotoRoute(array('action'=>'index'));
    }          

    public function previewexAction(){
        if(!$this->getRequest()->isPost()) return;
        $table = Engine_Api::_()->getDbTable('companies','webmix'); 
        $file_id = $table->setPhoto($_FILES['image']); 
        $type = 'thumb.normal';
        $file = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id, $type);
            if( !$file ) {
                return ;
            } 
        //get normal photo to save           
        $file_url = $file->map();
        $this->view->file_url = $file_url;
        $this->view->file_id = $file_id;
        
        //get full size photo to preview
        $preview = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id);
        $preview_url = $preview->map();
        $this->view->preview_url = $preview_url;                
    }
     
}
